package com.neusoft.hifly.commons.lang;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Title: 核心类库
 * <p>
 * Description: Unicode转中文/中文转Unicode
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
public class UnicodeUtil {
	/**
	 * 中文转Unicode
	 *
	 * @param string
	 *            字符串
	 * @return 转码
	 */
	public static String unicodeEncode(final String string) {
		final char[] utfBytes = string.toCharArray();
		String unicodeBytes = "";
		for (final char utfByte : utfBytes) {
			String hexB = Integer.toHexString(utfByte);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "\\u" + hexB;
		}
		return unicodeBytes;
	}

	/**
	 * Unicode转中文
	 *
	 * @param str
	 *            字符串
	 * @return 转码
	 */
	public static String unicodeDecode(String string) {
		final Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
		final Matcher matcher = pattern.matcher(string);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			string = string.replace(matcher.group(1), ch + "");
		}
		return string;
	}

	//测试
	public static void main(final String[] args) {
		final String sourceData = "这是原始的数据！！！";
		final String unicodeEncode = UnicodeUtil.unicodeEncode(sourceData);
		System.out.println("编码结果：" + unicodeEncode);

		final String unicodeDecode = UnicodeUtil.unicodeDecode(unicodeEncode);
		System.out.println("解码结果：" + unicodeDecode);

		System.out.println("解码结果：" + UnicodeUtil.unicodeDecode("nQN02x+D9G/brWVbToBFGA=="));
	}
}
